package api

import (
	_ "jtdevice/api/controller"
	_ "jtdevice/api/device"
	"jtdevice/configs"
	"jtdevice/pkg/router"
	"log"
	"net/http"

	"github.com/gin-contrib/pprof"
	"github.com/gin-gonic/gin"
)

type Options struct {
	Timeout int
	Port    int
	Root    string
	Public  string
}

// Run
func Run() error {
	var opts Options
	if err := configs.GViper.UnmarshalKey("serve", &opts); err != nil {
		return err
	}
	// gin.SetMode(gin.ReleaseMode)
	engine := gin.Default()
	engine.Use(gin.Logger()) // 日志
	// r.Use(middleware.Cors()) // 跨域
	pprof.Register(engine)
	r := engine.Group(opts.Root)
	r.StaticFS("/public", http.Dir(configs.Public.String()))
	router.Use(r, r, r.Group("/api"))
	s := router.ListenAndServe(engine, opts.Port, opts.Timeout)
	log.Printf("%s server listening at: %s\n", configs.AppName, s.Addr)
	return nil
}

func Shutdown() {
	router.Release()
}
